#!/bin/bash

if [ $# != 4 ];then
echo "opensource/build param error: [$1][$2][$3][$4]!" 
exit 1
fi

HOST=$1
if [ $HOST = "unknown" ];then 
HOST=
fi

LINKTYPE=$2
OUTPUT=$3
BUILD_SYSTEM=$4

OPENSOURCE_DIR=$(dirname $0)
RM=/bin/rm
##################################
#####  指定编译目录
##################################
SQLITE_DIR=$OPENSOURCE_DIR/sqlite-3871
CURL_DIR=$OPENSOURCE_DIR/curl-7.42.1
LIBCONFIG_DIR=$OPENSOURCE_DIR/libconfig-1.4.9
CJSON_DIR=$OPENSOURCE_DIR/cJSON
TINYXML_DIR=$OPENSOURCE_DIR/tinyxml-2.6.2
LOG4Z_DIR=$OPENSOURCE_DIR/log4z
TINYALSA_DIR=$OPENSOURCE_DIR/tinyalsa

##################################
####  build sqlite
##################################
cd $SQLITE_DIR
if [ $BUILD_SYSTEM = "OS_UNIX" ];then
autoreconf -ivf
./configure --prefix=$OUTPUT --host=$HOST
make -j
make install
else
echo -e "\033[33m\033WARNING: not build sqlite on system: $BUILD_SYSTEM\033[0m"
fi
cd ..

##################################
####  build curl
##################################
cd $CURL_DIR
if [ $BUILD_SYSTEM = "OS_UNIX" ];then
./configure --prefix=$OUTPUT --host=$HOST --disable-ldap  --disable-ldaps \
--without-zlib --without-ssl --without-libidn 
make -j
make install
else
echo -e "\033[33m\033WARNING: not build curl on system: $BUILD_SYSTEM\033[0m"
fi
cd ..

##################################
####  build libconfig
##################################
cd $LIBCONFIG_DIR
./configure --prefix=$OUTPUT --host=$HOST
make -j
make install
cd ..

##################################
####  build cjson
##################################
cd $CJSON_DIR
make HOST=$HOST LINKTYPE=$LINKTYPE PREFIX=$OUTPUT
make test HOST=$HOST LINKTYPE=$LINKTYPE PREFIX=$OUTPUT
make install HOST=$HOST LINKTYPE=$LINKTYPE PREFIX=$OUTPUT
cd ..

##################################
####  build tinyxml
##################################
cd $TINYXML_DIR
make HOST=$HOST LINKTYPE=$LINKTYPE PREFIX=$OUTPUT
make install HOST=$HOST LINKTYPE=$LINKTYPE PREFIX=$OUTPUT
cd ..

##################################
####  build log4z
##################################
cd $LOG4Z_DIR
make HOST=$HOST LINKTYPE=$LINKTYPE PREFIX=$OUTPUT
make install HOST=$HOST LINKTYPE=$LINKTYPE PREFIX=$OUTPUT
cd ..

##################################
####  build tinyalsa
##################################
if [ $BUILD_SYSTEM != "OS_CYGWIN" ];then
cd $TINYALSA_DIR
make HOST=$HOST LINKTYPE=$LINKTYPE PREFIX=$OUTPUT
make install HOST=$HOST LINKTYPE=$LINKTYPE PREFIX=$OUTPUT
cd ..
fi

##################################
####  delete lib we don't need
##################################
if [ "$BUILD_SYSTEM" = "OS_UNIX" ];then
chmod a+x  $OUTPUT
fi
${RM} -rf $OUTPUT/lib/*.la
echo "rm dynamic libraries!"
if [ "$LINKTYPE" = "shared" ]
then
${RM} -rf $OUTPUT/lib/*.a
else
${RM} -rf $OUTPUT/lib/*.so*
fi

